#ifndef OPEN_LCD_H
#define OPEN_LCD_H
#include "Box.h"
#include "Container.h"

#include <string>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#include <mutex>

#include <sys/mman.h>
using namespace std;

class Lcd : public Box
{
private:
    int fd = -1;
    int *backBuffer = nullptr; // 后台缓冲区

    static bool isInt;

public:
    Lcd(const char path[] = "/dev/fb0", int width = 800, int height = 480) : Box(width, height)
    {
        if (isInt)
        {
            cout << "错误 重复初始化Lcd设备" << endl;
            exit(-1);
        }
        fd = open(path, O_RDWR);
        if (fd == -1)
        {
            cout << "Lcd初始化失败" << endl;
            exit(-1);
        }
        store = (int *)mmap(NULL, height * width * 4, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
        if (store == MAP_FAILED)
        {
            cout << "内存映射初始化失败" << endl;
            exit(-1);
        }
        backBuffer = new int[width * height];
        if (backBuffer == nullptr)
        {
            cout << "初始化缓冲区失败" << endl;
        }
        isInt = true;
        cout << "lcd初始化成功" << endl;
    }
    ~Lcd()
    {
        if (fd != -1)
            close(fd);
        if (store != MAP_FAILED)
            munmap(store, height * width * 4);
        if (backBuffer != nullptr)
            delete[] backBuffer;
        isInt = false;
        cout << "Lcd设备得到释放" << endl;
    }

    // 删除拷贝构造函数和赋值运算符
    Lcd(const Lcd &other) = delete;
    Lcd &operator=(const Lcd &other) = delete;

    // 返回函数
    int get_fd() { return fd; }
    bool isValid() { return fd != -1 && store != MAP_FAILED; }

    // 复杂函数
    int clear(unsigned int color = 0x00000000);
    int set_store(Container &other);
};

#endif